package com.alibaba.citrus.cr.platform.enhance.repository.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.platform.enhance.repository.DimensionQueryRepository;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;

import com.epoch.app.crplatformenhance.dimension.dto.LoadDimensionRequest;
import com.epoch.app.crplatformenhance.dimension.dto.QueryListByPriorityRequest;
import com.epoch.app.crplatformenhance.dimension.model.Dimension;
import com.epoch.app.crplatformenhance.dimension.service.DimensionService;
import com.epoch.app.crplatformenhance.model.dto.DimensionLoadListRequest;
import com.epoch.app.crplatformenhance.model.dto.DimensionPageQueryRequest;
import com.epoch.app.crplatformenhance.model.dto.DimensionPageQueryResponse;
import com.epoch.app.crplatformenhance.model.dto.ExecuteActionDesc;
import com.epoch.app.crplatformenhance.model.enums.RuleTypeEnum;
import com.epoch.app.crplatformenhance.sdo.DimensionSDO;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class DimensionQueryRepositoryImpl implements DimensionQueryRepository {

    @Resource
    private DimensionService dimensionService;

    @Override
    public Result<List<DimensionPageQueryResponse>> pageQuery(DimensionPageQueryRequest request) {
        DimensionLoadListRequest dimensionLoadListRequest = dimensionLoadListRequestConverter(request);

        Result<List<Dimension>> listResult = dimensionService.loadDimensionList(dimensionLoadListRequest);
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return new Result<>();
        }
        List<DimensionPageQueryResponse> pageQueryResponses = listResult.getResult().stream()
                .map(this::DimensionPageQueryResponseConverter).collect(Collectors.toList());
        return Result.listSuccess(pageQueryResponses, listResult.getTotal());
    }

    @Override
    public DimensionSDO query(String id) {
        LoadDimensionRequest request = new LoadDimensionRequest();
        if (!StringUtils.isEmpty(id)) {
            request.setId(Long.parseLong(id));
        }
        Dimension dimension = dimensionService.loadDimension(request);
        DimensionSDO dimensionSDO = new DimensionSDO();
        dimensionSDO.setId(dimension.getId());
        dimensionSDO.setCode(dimension.getCode());
        dimensionSDO.setValue(dimension.getValue());
        dimensionSDO.setValueName(dimension.getValueName());
        dimensionSDO.setRuleName(dimension.getRuleName());
        List<String> list = new ArrayList<>();
        if (!StringUtils.isEmpty(dimension.getRuleName()) && dimension.getRuleName().equals(RuleTypeEnum.TIME_FRAME.getCode())) {
            String substring = dimension.getRuleValue().substring(dimension.getRuleValue().indexOf("[") + 1, dimension.getRuleValue().indexOf("]") - 1).replace("\"", "").trim();
            String[] split = substring.split(",");
            list.add(split[0]);
            list.add(split[1]);
        } else {
            dimensionSDO.setRuleValue(dimension.getRuleValue());
        }
        dimensionSDO.setExt1(list);
        dimensionSDO.setStatus(dimension.getStatus());
        List<String> timeList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT);
        if (dimension.getValidBeginTime() != null) {
            timeList.add(sdf.format(dimension.getValidBeginTime()));
        }
        if (dimension.getValidEndTime() != null) {
            timeList.add(sdf.format(dimension.getValidEndTime()));
        }
        dimensionSDO.setValid(timeList);
        dimensionSDO.setValidEndTime(dimension.getValidEndTime());
        if (null != dimension.getExecuteAction()) {
            ExecuteActionDesc executeActionDesc = new ExecuteActionDesc();
            if (dimension.getExecuteAction()) {
                executeActionDesc.setValue(true);
                executeActionDesc.setText("开启校验");
            } else {
                executeActionDesc.setValue(false);
                executeActionDesc.setText("关闭校验");
            }
            dimensionSDO.setExecuteActionDesc(executeActionDesc);
        }
        dimensionSDO.setExecuteAction(dimension.getExecuteAction());
        dimensionSDO.setStrategyId(dimension.getStrategyId());
        dimensionSDO.setDetails(dimension.getDetails());
        dimensionSDO.setCreator(dimension.getCreator());
        dimensionSDO.setGmtCreate(dimension.getGmt_create());
        dimensionSDO.setUpdater(dimension.getUpdater());
        dimensionSDO.setGmtModified(dimension.getGmt_modified());
        dimensionSDO.setPriority(dimension.getPriority());
        return dimensionSDO;
    }

    @Override
    public Result<List<Dimension>> queryListByPriority(QueryListByPriorityRequest request) {
        Result<List<Dimension>> listResult = dimensionService.queryListByPriority(request);
        return listResult;
    }

    private DimensionPageQueryResponse DimensionPageQueryResponseConverter(Dimension dimension) {
        DimensionPageQueryResponse dimensionPageQueryResponse = new DimensionPageQueryResponse();
        if (null != dimension.getId()) {
            dimensionPageQueryResponse.setId(String.valueOf(dimension.getId()));
        }
        dimensionPageQueryResponse.setDimensionCode(dimension.getCode());
        dimensionPageQueryResponse.setDimensionValue(dimension.getValue());
        dimensionPageQueryResponse.setRule(dimension.getRuleName());
        dimensionPageQueryResponse.setRuleValue(dimension.getRuleValue());
        dimensionPageQueryResponse.setStatus(dimension.getStatus());
        dimensionPageQueryResponse.setValidBeginTime(dimension.getValidBeginTime());
        dimensionPageQueryResponse.setValidEndTime(dimension.getValidEndTime());
        dimensionPageQueryResponse.setExecuteAction(dimension.getExecuteAction());
        dimensionPageQueryResponse.setStrategyId(dimension.getStrategyId());
        dimensionPageQueryResponse.setDetails(dimension.getDetails());
        dimensionPageQueryResponse.setCreator(dimension.getCreator());
        dimensionPageQueryResponse.setUpdater(dimension.getUpdater());
        return dimensionPageQueryResponse;
    }

    private DimensionLoadListRequest dimensionLoadListRequestConverter(DimensionPageQueryRequest request) {
        DimensionLoadListRequest dimensionLoadListRequest = new DimensionLoadListRequest();
        dimensionLoadListRequest.setId(request.getId());
        dimensionLoadListRequest.setCode(request.getDimensionCode());
        dimensionLoadListRequest.setValue(request.getDimensionValue());
        dimensionLoadListRequest.setRuleName(request.getRule());
        dimensionLoadListRequest.setRuleValue(request.getRuleValue());
        dimensionLoadListRequest.setStatus(request.getStatus());
        dimensionLoadListRequest.setValidBeginTime(request.getValidBeginTime());
        dimensionLoadListRequest.setValidEndTime(request.getValidEndTime());
        dimensionLoadListRequest.setExecuteAction(request.getExecuteAction());
        dimensionLoadListRequest.setStrategyId(request.getStrategyId());
        dimensionLoadListRequest.setDetails(request.getDetails());
        dimensionLoadListRequest.setPriority(request.getPriority());
        dimensionLoadListRequest.setCreator(request.getCreator());
        dimensionLoadListRequest.setModifier(request.getUpdater());
        dimensionLoadListRequest.setStart(request.getStart());
        dimensionLoadListRequest.setLimit(request.getLimit());
        dimensionLoadListRequest.setDir("gmtCreate");
        dimensionLoadListRequest.setAsc(false);
        return dimensionLoadListRequest;
    }

}
